package com.zp.oj.judge.CodeSandBox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zp.oj.common.ErrorCode;
import com.zp.oj.exception.BusinessException;
import com.zp.oj.judge.CodeSandBox.CodeSandBox;
import com.zp.oj.judge.model.ExecuteCodeRequest;
import com.zp.oj.judge.model.ExecuteCodeSandResponse;

import javax.json.Json;

/**
 * 远程代码沙箱
 */
public class RemoteCodeSandBox implements CodeSandBox {
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_SECRET_KEY = "DJASDIU2903UER0FJW0FDNXSJCFVBDSIF28938"; // SECRETKEY
    @Override
    public ExecuteCodeSandResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        // String url = "http://localhost:8090/executeCode";
        String url = "http://192.168.102.128:8090/executeCode";
        String requestParam = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_SECRET_KEY)
                                .body(requestParam)
                                .execute()
                                .body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.OPENAPI_ERROR, "调用接口失败" + responseStr);
        }
        ExecuteCodeSandResponse response = JSONUtil.toBean(responseStr, ExecuteCodeSandResponse.class);
        return response;
    }
}
